package io.hots.strategy;

import io.hots.enums.BizCodeEnum;
import io.hots.exception.BizException;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @author yueshibin@cetcbigdata.com
 * @date 2022/9/6 3:11 下午
 */
public class CustomDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {

        //获取用户id或码第⼀位，即库位
        String codePrefix = shardingValue.getValue().substring(0, 1);

        for (String targetName : availableTargetNames) {
            //获取库名的最后⼀位，真实配置的ds
            String targetNameSuffix = targetName.substring(targetName.length() - 1);
            //如果⼀致则返回
            if (codePrefix.equals(targetNameSuffix)) {
                return targetName;
            }
        }

       //抛异常
       throw new BizException(BizCodeEnum.DB_ROUTE_NOT_FOUND);

    } }
